<template>
  <div class="addPersonnel-container-padding">
    <div v-if="!disabled" class="buttonList">
      <!-- <el-button type="primary" @click="save">暂存</el-button> -->
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <div class="card">
      <div class="title">人员基本信息</div>
      <el-form
        ref="baseInfoRef"
        :inline="true"
        :model="userBaseInfo"
        :rules="rules"
        :disabled="disabled"
        class="demo-form-inline"
        label-width="auto"
      >
        <el-form-item label="人员名称：" prop="name">
          <el-input
            v-model="userBaseInfo.name"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="员工编号：">
          <el-input
            v-model="userBaseInfo.employeeNumber"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系方式：" prop="contactInfo">
          <el-input
            v-model="userBaseInfo.contactInfo"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系地址：">
          <el-input
            v-model="userBaseInfo.contactAddress"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="card margin-top20">
      <div class="title">在编信息</div>
      <el-form
        ref="onlineInfoRef"
        :inline="true"
        :model="userBaseInfo"
        :rules="rules"
        :disabled="disabled"
        class="demo-form-inline"
        label-width="auto"
      >
        <el-form-item label="进站时间：" prop="entryTime">
          <el-date-picker
            v-model="userBaseInfo.entryTime"
            type="date"
            placeholder="请选择"
            clearable
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 323px"
          />
        </el-form-item>
        <el-form-item label="工作状态：">
          <el-select v-model="userBaseInfo.workStatus" placeholder="请选择">
            <el-option
              v-for="item in workOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作单位：">
          <el-select v-model="userBaseInfo.workUnitId" placeholder="请选择">
            <el-option
              v-for="item in unitOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职称：">
          <el-input
            v-model="userBaseInfo.title"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="职务：">
          <el-input
            v-model="userBaseInfo.position"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="专家等级：">
          <el-select v-model="userBaseInfo.expertLevel" placeholder="请选择">
            <el-option
              v-for="item in expertLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="card margin-top20">
      <div class="title">教育信息</div>
      <div class="flexBox">
        <div class="formCard">
          <div class="formCardtitle">博士阶段</div>
          <el-form
            :model="userBaseInfo"
            label-width="auto"
            :disabled="disabled"
            class="cardForm"
          >
            <el-form-item label="毕业院校：">
              <el-input v-model="userBaseInfo.phdGradUniversity" />
            </el-form-item>
            <el-form-item label="专业：">
              <el-input v-model="userBaseInfo.phdMajor" />
            </el-form-item>
          </el-form>
        </div>
        <div class="formCard">
          <div class="formCardtitle">研究生阶段</div>
          <el-form
            :model="userBaseInfo"
            label-width="auto"
            :disabled="disabled"
            class="cardForm"
          >
            <el-form-item label="毕业院校：">
              <el-input v-model="userBaseInfo.masterGradUniversity" />
            </el-form-item>
            <el-form-item label="专业：">
              <el-input v-model="userBaseInfo.masterMajor" />
            </el-form-item>
          </el-form>
        </div>
        <div class="formCard">
          <div class="formCardtitle">本科阶段</div>
          <el-form
            :model="userBaseInfo"
            label-width="auto"
            :disabled="disabled"
            class="cardForm"
          >
            <el-form-item label="毕业院校：">
              <el-input v-model="userBaseInfo.bachelorGradUniversity" />
            </el-form-item>
            <el-form-item label="专业：">
              <el-input v-model="userBaseInfo.bachelorMajor" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="card margin-top20">
      <div class="title">附件信息</div>
      <uploadFile :file-list="file" @upload:success="handleUpload" />
    </div>
    <div v-if="operation" class="card margin-top20">
      <div class="title margin-bottom0">操作日志</div>
      <vxe-grid v-bind="gridOptions" :height="height">
        <template #pager>
          <!--使用 pager 插槽-->
          <vxe-pager
            v-model:current-page="tablePage.currentPage"
            v-model:page-size="tablePage.pageSize"
            :layouts="[
              'Sizes',
              'PrevJump',
              'PrevPage',
              'Number',
              'NextPage',
              'NextJump',
              'FullJump',
              'Total',
            ]"
            :total="tablePage.total"
            @page-change="handlePageChange"
          />
        </template>
      </vxe-grid>
    </div>
  </div>
</template>

<script setup lang="ts">
  import {
    reactive,
    ref,
    withDefaults,
    defineProps,
    onMounted,
    computed,
  } from 'vue'
  import type { FormRules, FormInstance, UploadUserFile } from 'element-plus'
  import uploadFile from './uploadFile.vue'
  import { useRoute } from 'vue-router'
  import { gridOptions } from '../table/column'
  import { VxeGridProps, VxePagerEvents } from 'vxe-table'
  import {
    addPersonnel,
    updatePersonnel,
    getPersonnelInfo,
  } from '@/api/postdoctor'
  import { useDictStore } from '@/store/modules/dict'
  import { getSimpleDeptList } from '@/api/system/dept'
  import { isPhone } from '@/utils/validate'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const dictStore = useDictStore()
  const workOptions = computed(() =>
    dictStore.getDictType('postdoc_work_status')
  )
  const unitOptions = ref([])
  const getDptList = () => {
    getSimpleDeptList().then((res: any) => {
      unitOptions.value = res.data
    })
  }
  const getInfo = () => {
    getPersonnelInfo({ id: id.value, getType: 2 }).then((res) => {
      for (const key in res.data) {
        userBaseInfo[key] = res.data[key]
        file.value = userBaseInfo.relatedDocuments.map((item) => {
          return {
            name: item.fileName,
            url: item.fileUrl,
            type: item.fileType,
            id: item.fileId,
          }
        })
      }
    })
  }

  const route = useRoute()
  const id = ref('')
  onMounted(() => {
    getDptList()
    id.value = route.query.id
    if (id.value) {
      getInfo()
    }
  })

  const props = withDefaults(
    defineProps<{
      disabled?: boolean
      operation?: boolean
      userInfo?: any
    }>(),
    {
      disabled: false,
      operation: false,
      userInfo: {},
    }
  )

  const baseInfoRef = ref<FormInstance>()
  const onlineInfoRef = ref<FormInstance>()
  const { closeTabNavigate } = useCloseTabNavigate()

  const userBaseInfo = reactive({
    name: '',
    employeeNumber: '',
    contactInfo: '',
    contactAddress: '',
    entryTime: '',
    workStatus: '',
    workUnitId: '',
    workUnitName: '',
    position: '',
    title: '',
    expertLevel: '',
    phdGradUniversity: '',
    phdMajor: '',
    masterGradUniversity: '',
    masterMajor: '',
    bachelorGradUniversity: '',
    bachelorMajor: '',
    relatedDocuments: [],
  })

  const expertLevelOptions = ref([
    {
      label: '一级',
      value: '0',
    },
    {
      label: '二级',
      value: '1',
    },
    {
      label: '三级',
      value: '2',
    },
    {
      label: '四级',
      value: '3',
    },
  ])

  const file = ref([])
  const handleUpload = (data: UploadUserFile[]) => {
    file.value = data
  }

  const validatePhone = (rule, value, callback) => {
    if (value && !isPhone(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }

  const rules = reactive<FormRules>({
    contactInfo: [{ validator: validatePhone, trigger: 'blur' }],
  })

  // 保存为草稿
  // const save = async () => {
  //   console.log('baocun')
  //   emeit('save', true)
  //   await baseInfoRef.value.resetFields()
  //   await onlineInfoRef.value.resetFields()
  // }
  // 提交表单
  const submit = async () => {
    const isOk = [false, false]
    await baseInfoRef.value.validate((valid) => {
      isOk[0] = valid
    })
    await onlineInfoRef.value.validate((valid) => {
      isOk[1] = valid
    })
    if (isOk[0] && isOk[1]) {
      // emeit('save', true)
      userBaseInfo.relatedDocuments = file.value.map((item) => {
        return {
          fileName: item.name,
          fileId: item.id,
          fileUrl: item.url,
          businessType: 'POSTDOC_PERSON_ATTACHMENT',
          fileType: item.type,
          businessId: '13',
        }
      })
      userBaseInfo.workUnitName = unitOptions.value.find(
        (item) => item.value == userBaseInfo.workUnitId
      )?.label

      if (id.value) {
        userBaseInfo.id = id.value
        updatePersonnel(userBaseInfo).then((res) => {
          ElMessage.success('修改成功')
          closeTabNavigate({ name: 'Personnel' })
        })
      } else {
        addPersonnel(userBaseInfo).then((res: any) => {
          ElMessage.success('提交成功')
          closeTabNavigate({ name: 'Personnel' })
        })
      }
    }
  }

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const handlePageChange: VxePagerEvents.PageChange = ({
    currentPage,
    pageSize,
  }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    // findList()
  }

  const height = ref(0)
  interface BaseTableHeight {
    (padding: number): number
  }
  const $baseTableHeight = inject<BaseTableHeight>('$baseTableHeight')
  onBeforeMount(() => {
    window.addEventListener('resize', handleHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleHeight)
  })

  const handleHeight = () => {
    height.value = $baseTableHeight(0)
  }
</script>

<style scoped lang="scss">
  $margin-bottom: 20px;

  .buttonList {
    display: flex;
    justify-content: end;
    padding-bottom: $margin-bottom;
    border-bottom: 1px solid #edeff2;
    margin-bottom: $margin-bottom;
  }

  .card {
    .title {
      border-radius: 2px;
      border-left: 5px solid #1890ff;
      height: 28px;
      background: #f7f8f9;
      font-weight: 500;
      font-size: 14px;
      color: #606266;
      padding-left: 12px;
      line-height: 28px;
      margin-bottom: $margin-bottom;
    }
  }

  .margin-bottom0 {
    margin-bottom: 0 !important;
  }

  .margin-top20 {
    margin-top: 20px;
  }

  .demo-form-inline {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;

    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .flexBox {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column-gap: 20px;
  }

  .formCard {
    border-radius: 4px;

    .formCardtitle {
      background: #e7f3ff;
      font-size: 12px;
      color: #7d8398;
      padding-left: 10px;
      height: 24px;
      line-height: 24px;
      border-radius: 4px 4px 0 0;
    }

    .cardForm {
      background: #f6fbff;
      padding: 20px;
      border-radius: 0 0 4px 4px;

      .el-input {
        // --el-input-width: 421px;
      }
    }
  }
</style>
